using System;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
using DocumentCreationSystem.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 工具API配置服务接口
    /// </summary>
    public interface IToolApiConfigService
    {
        /// <summary>
        /// 获取工具API配置
        /// </summary>
        /// <returns>工具API配置</returns>
        Task<ToolApiConfig> GetConfigAsync();

        /// <summary>
        /// 保存工具API配置
        /// </summary>
        /// <param name="config">工具API配置</param>
        /// <returns>保存结果</returns>
        Task<(bool Success, string Message)> SaveConfigAsync(ToolApiConfig config);

        /// <summary>
        /// 测试搜索API
        /// </summary>
        /// <param name="query">搜索查询</param>
        /// <returns>测试结果</returns>
        Task<(bool Success, string Result, string ErrorMessage)> TestSearchApiAsync(string query);

        /// <summary>
        /// 测试翻译API
        /// </summary>
        /// <param name="text">要翻译的文本</param>
        /// <param name="targetLanguage">目标语言</param>
        /// <returns>测试结果</returns>
        Task<(bool Success, string Result, string ErrorMessage)> TestTranslateApiAsync(string text, string targetLanguage = "en");
    }

    /// <summary>
    /// 工具API配置服务实现
    /// </summary>
    public class ToolApiConfigService : IToolApiConfigService
    {
        private readonly ILogger<ToolApiConfigService> _logger;
        private readonly IConfiguration _configuration;
        private readonly string _configFilePath;

        public ToolApiConfigService(ILogger<ToolApiConfigService> logger, IConfiguration configuration)
        {
            _logger = logger;
            _configuration = configuration;
            
            // 配置文件路径
            var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            var configDir = Path.Combine(appDataPath, "DocumentCreationSystem");
            Directory.CreateDirectory(configDir);
            _configFilePath = Path.Combine(configDir, "tool_api_config.json");
        }

        /// <summary>
        /// 获取工具API配置
        /// </summary>
        public async Task<ToolApiConfig> GetConfigAsync()
        {
            try
            {
                // 首先尝试从文件加载
                if (File.Exists(_configFilePath))
                {
                    var json = await File.ReadAllTextAsync(_configFilePath);
                    var config = JsonSerializer.Deserialize<ToolApiConfig>(json);
                    if (config != null)
                    {
                        _logger.LogInformation("工具API配置已从文件加载");
                        return config;
                    }
                }

                // 如果文件不存在，从appsettings.json加载默认配置
                var defaultConfig = LoadFromAppSettings();
                _logger.LogInformation("工具API配置已从默认设置加载");
                return defaultConfig;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载工具API配置失败");
                return new ToolApiConfig(); // 返回默认配置
            }
        }

        /// <summary>
        /// 保存工具API配置
        /// </summary>
        public async Task<(bool Success, string Message)> SaveConfigAsync(ToolApiConfig config)
        {
            try
            {
                // 不进行严格验证，允许保存空的APIkey
                // 工具的启用状态将根据APIkey是否为空来自动确定

                // 序列化并保存到文件
                var options = new JsonSerializerOptions
                {
                    WriteIndented = true,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                };

                var json = JsonSerializer.Serialize(config, options);
                await File.WriteAllTextAsync(_configFilePath, json);

                // 记录工具可用性状态
                var availability = config.GetToolAvailability();
                _logger.LogInformation($"工具API配置已保存到: {_configFilePath}");
                _logger.LogInformation($"工具可用性 - 搜索: {availability.IsSearchEnabled}, 翻译: {availability.IsTranslateEnabled}, 天气: {availability.IsWeatherEnabled}, 新闻: {availability.IsNewsEnabled}");

                return (true, "工具API配置保存成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存工具API配置失败");
                return (false, $"保存失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 测试搜索API
        /// </summary>
        public async Task<(bool Success, string Result, string ErrorMessage)> TestSearchApiAsync(string query)
        {
            try
            {
                var config = await GetConfigAsync();
                var searchConfig = config.SearchConfig;

                // 验证搜索配置
                var (isValid, errorMessage) = searchConfig.Validate();
                if (!isValid)
                {
                    return (false, string.Empty, errorMessage);
                }

                // 根据搜索引擎类型进行测试
                switch (searchConfig.SearchEngine.ToLower())
                {
                    case "google":
                        return await TestGoogleSearchAsync(query, searchConfig.GoogleConfig, searchConfig.ResultCount);
                    case "bing":
                        return await TestBingSearchAsync(query, searchConfig.BingConfig, searchConfig.ResultCount);
                    case "serper":
                        return await TestSerperSearchAsync(query, searchConfig.SerperConfig, searchConfig.ResultCount);
                    default:
                        return (false, string.Empty, "不支持的搜索引擎类型");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "测试搜索API失败");
                return (false, string.Empty, $"测试失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 测试翻译API
        /// </summary>
        public async Task<(bool Success, string Result, string ErrorMessage)> TestTranslateApiAsync(string text, string targetLanguage = "en")
        {
            try
            {
                var config = await GetConfigAsync();
                var translateConfig = config.TranslateConfig;

                // 验证翻译配置
                var (isValid, errorMessage) = translateConfig.Validate();
                if (!isValid)
                {
                    return (false, string.Empty, errorMessage);
                }

                // 根据翻译服务类型进行测试
                switch (translateConfig.TranslateService.ToLower())
                {
                    case "google":
                        return await TestGoogleTranslateAsync(text, targetLanguage, translateConfig.GoogleConfig);
                    case "baidu":
                        return await TestBaiduTranslateAsync(text, targetLanguage, translateConfig.BaiduConfig);
                    case "tencent":
                        return await TestTencentTranslateAsync(text, targetLanguage, translateConfig.TencentConfig);
                    default:
                        return (false, string.Empty, "不支持的翻译服务类型");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "测试翻译API失败");
                return (false, string.Empty, $"测试失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 从appsettings.json加载默认配置
        /// </summary>
        private ToolApiConfig LoadFromAppSettings()
        {
            var config = new ToolApiConfig();

            // 加载搜索API配置
            var searchSection = _configuration.GetSection("ToolApi:Search");
            if (searchSection.Exists())
            {
                config.SearchConfig.SearchEngine = searchSection["Engine"] ?? "Google";
                config.SearchConfig.ResultCount = int.Parse(searchSection["ResultCount"] ?? "10");
                config.SearchConfig.Language = searchSection["Language"] ?? "zh-CN";
                config.SearchConfig.SafeSearch = bool.Parse(searchSection["SafeSearch"] ?? "true");

                // Google搜索配置
                var googleSection = searchSection.GetSection("Google");
                if (googleSection.Exists())
                {
                    config.SearchConfig.GoogleConfig.ApiKey = googleSection["ApiKey"] ?? string.Empty;
                    config.SearchConfig.GoogleConfig.SearchEngineId = googleSection["SearchEngineId"] ?? string.Empty;
                }

                // Bing搜索配置
                var bingSection = searchSection.GetSection("Bing");
                if (bingSection.Exists())
                {
                    config.SearchConfig.BingConfig.ApiKey = bingSection["ApiKey"] ?? string.Empty;
                }

                // Serper搜索配置
                var serperSection = searchSection.GetSection("Serper");
                if (serperSection.Exists())
                {
                    config.SearchConfig.SerperConfig.ApiKey = serperSection["ApiKey"] ?? string.Empty;
                }
            }

            // 加载翻译API配置
            var translateSection = _configuration.GetSection("ToolApi:Translate");
            if (translateSection.Exists())
            {
                config.TranslateConfig.TranslateService = translateSection["Service"] ?? "Google";

                // Google翻译配置
                var googleTranslateSection = translateSection.GetSection("Google");
                if (googleTranslateSection.Exists())
                {
                    config.TranslateConfig.GoogleConfig.ApiKey = googleTranslateSection["ApiKey"] ?? string.Empty;
                }

                // 百度翻译配置
                var baiduTranslateSection = translateSection.GetSection("Baidu");
                if (baiduTranslateSection.Exists())
                {
                    config.TranslateConfig.BaiduConfig.AppId = baiduTranslateSection["AppId"] ?? string.Empty;
                    config.TranslateConfig.BaiduConfig.SecretKey = baiduTranslateSection["SecretKey"] ?? string.Empty;
                }

                // 腾讯翻译配置
                var tencentTranslateSection = translateSection.GetSection("Tencent");
                if (tencentTranslateSection.Exists())
                {
                    config.TranslateConfig.TencentConfig.SecretId = tencentTranslateSection["SecretId"] ?? string.Empty;
                    config.TranslateConfig.TencentConfig.SecretKey = tencentTranslateSection["SecretKey"] ?? string.Empty;
                }
            }

            // 加载其他API配置
            var weatherSection = _configuration.GetSection("ToolApi:Weather");
            if (weatherSection.Exists())
            {
                config.WeatherConfig.ApiKey = weatherSection["ApiKey"] ?? string.Empty;
            }

            var newsSection = _configuration.GetSection("ToolApi:News");
            if (newsSection.Exists())
            {
                config.NewsConfig.ApiKey = newsSection["ApiKey"] ?? string.Empty;
            }

            return config;
        }

        /// <summary>
        /// 测试Google搜索API
        /// </summary>
        private async Task<(bool Success, string Result, string ErrorMessage)> TestGoogleSearchAsync(
            string query, GoogleSearchConfig config, int resultCount)
        {
            // 这里应该实现实际的Google搜索API调用
            // 为了演示，返回模拟结果
            await Task.Delay(1000); // 模拟网络延迟
            
            if (string.IsNullOrEmpty(config.ApiKey) || string.IsNullOrEmpty(config.SearchEngineId))
            {
                return (false, string.Empty, "Google搜索API配置不完整");
            }

            var result = $"Google搜索测试成功！\n查询: {query}\n结果数量: {resultCount}\n" +
                        "注意：这是测试结果，实际搜索功能需要完整的API实现。";
            
            return (true, result, string.Empty);
        }

        /// <summary>
        /// 测试Bing搜索API
        /// </summary>
        private async Task<(bool Success, string Result, string ErrorMessage)> TestBingSearchAsync(
            string query, BingSearchConfig config, int resultCount)
        {
            await Task.Delay(1000);
            
            if (string.IsNullOrEmpty(config.ApiKey))
            {
                return (false, string.Empty, "Bing搜索API密钥未配置");
            }

            var result = $"Bing搜索测试成功！\n查询: {query}\n结果数量: {resultCount}";
            return (true, result, string.Empty);
        }

        /// <summary>
        /// 测试Serper搜索API
        /// </summary>
        private async Task<(bool Success, string Result, string ErrorMessage)> TestSerperSearchAsync(
            string query, SerperSearchConfig config, int resultCount)
        {
            await Task.Delay(1000);
            
            if (string.IsNullOrEmpty(config.ApiKey))
            {
                return (false, string.Empty, "Serper API密钥未配置");
            }

            var result = $"Serper搜索测试成功！\n查询: {query}\n结果数量: {resultCount}";
            return (true, result, string.Empty);
        }

        /// <summary>
        /// 测试Google翻译API
        /// </summary>
        private async Task<(bool Success, string Result, string ErrorMessage)> TestGoogleTranslateAsync(
            string text, string targetLanguage, GoogleTranslateConfig config)
        {
            await Task.Delay(1000);
            
            if (string.IsNullOrEmpty(config.ApiKey))
            {
                return (false, string.Empty, "Google翻译API密钥未配置");
            }

            var result = $"Google翻译测试成功！\n原文: {text}\n目标语言: {targetLanguage}\n翻译结果: [模拟翻译结果]";
            return (true, result, string.Empty);
        }

        /// <summary>
        /// 测试百度翻译API
        /// </summary>
        private async Task<(bool Success, string Result, string ErrorMessage)> TestBaiduTranslateAsync(
            string text, string targetLanguage, BaiduTranslateConfig config)
        {
            await Task.Delay(1000);
            
            if (string.IsNullOrEmpty(config.AppId) || string.IsNullOrEmpty(config.SecretKey))
            {
                return (false, string.Empty, "百度翻译API配置不完整");
            }

            var result = $"百度翻译测试成功！\n原文: {text}\n目标语言: {targetLanguage}";
            return (true, result, string.Empty);
        }

        /// <summary>
        /// 测试腾讯翻译API
        /// </summary>
        private async Task<(bool Success, string Result, string ErrorMessage)> TestTencentTranslateAsync(
            string text, string targetLanguage, TencentTranslateConfig config)
        {
            await Task.Delay(1000);
            
            if (string.IsNullOrEmpty(config.SecretId) || string.IsNullOrEmpty(config.SecretKey))
            {
                return (false, string.Empty, "腾讯翻译API配置不完整");
            }

            var result = $"腾讯翻译测试成功！\n原文: {text}\n目标语言: {targetLanguage}";
            return (true, result, string.Empty);
        }

        /// <summary>
        /// 检查特定工具是否可用
        /// </summary>
        public async Task<bool> IsToolEnabledAsync(string toolName)
        {
            try
            {
                var config = await GetConfigAsync();
                var availability = config.GetToolAvailability();

                return toolName.ToLower() switch
                {
                    "search" => availability.IsSearchEnabled,
                    "translate" => availability.IsTranslateEnabled,
                    "weather" => availability.IsWeatherEnabled,
                    "news" => availability.IsNewsEnabled,
                    _ => false
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"检查工具 {toolName} 可用性失败");
                return false;
            }
        }

        /// <summary>
        /// 获取所有工具的可用性状态
        /// </summary>
        public async Task<ToolAvailabilityStatus> GetToolAvailabilityAsync()
        {
            try
            {
                var config = await GetConfigAsync();
                return config.GetToolAvailability();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工具可用性状态失败");
                return new ToolAvailabilityStatus();
            }
        }
    }
}
